<template>
    <!-- <view class="title_bar">
		<Title-bar :titleCenter="true" :canBack="false" title="登录" />
	</view> -->
    <view class="login_page">
        <view class="title"> 欢迎使用学小乐 </view>
        <view class="login_form">
            <view class="login_form_item">
                <view class="left">
                    <image
                        :src="`${OSS_URL}/iconfont/phone_icon.png`"
                        mode=""
                        class="login_form_item_icon"
                    ></image>
                    <input
                        v-model="formatPhone"
                        class="input_box"
                        type="text"
                        placeholder="请输入手机号"
                        placeholder-style="color:rgba(169, 170, 181, 1);text-align: left;font-size:30rpx;"
                        @input="phoneDivision"
                    />
                </view>
            </view>
            <view class="login_form_item">
                <view class="left">
                    <image
                        :src="`${OSS_URL}/iconfont/code_icon.png`"
                        mode=""
                        class="login_form_item_icon"
                    ></image>
                    <input
                        v-model="loginForm.verifyCode"
                        class="input_box"
                        type="number"
                        placeholder="请输入验证码"
                        placeholder-style="color:rgba(169, 170, 181, 1);text-align: left;font-size:30rpx;"
                    />
                </view>
                <view class="code_btn">
                    <template v-if="codeTime > 0">
                        <text class="time_tip"
                            >{{ codeTimeContet }} <text class="gray">秒后重新发送</text></text
                        >
                    </template>
                    <template v-else>
                        <text @click="getCode">获取验证码</text>
                    </template>
                </view>
            </view>
            <button class="phone_btn" @click="handleLogin">登录</button>
        </view>
        <!-- 多层身份弹窗 -->
        <view class="picker_box">
            <uni-popup
                ref="popupRef"
                :is-mask-click="popup.maskClick"
                :animation="popup.animation"
                type="bottom"
            >
                <view class="popup_box" :style="{ 'margin-bottom': bottomHeight }">
                    <view class="header_title"> 请选择身份 </view>
                    <view class="method_list">
                        <view v-for="(i, idx) in userAdmin" :key="idx" class="item">
                            {{ i.adminTypeName }}
                        </view>
                    </view>
                </view>
            </uni-popup>
        </view>
    </view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { ref, computed, nextTick, onMounted, reactive } from 'vue';

import {
    getBindPhoneTypeApi,
    sendCodeMessageApi,
    getAdminTypeByPhoneApi,
    smsLoginApi,
    getUserInfoApi,
    getAuthUrlApi,
} from '@/api';
import { setCache } from '@/utils';
import { user} from '@/store'
const emits = defineEmits(['reloadFun']);
const OSS_URL = import.meta.env.VITE_OSS_HOST;
const { getUserInfo } = user()
const popupRef = ref(null);
const popup = reactive({ maskClick: true, animation: true });
const formatPhone = ref('');

const userAdmin = ref([]); // 用户身份列表
const loginForm = ref({
    adminType: 5,
    clientType: 'MOBILE',
    phone: '17833978268',
    verifyCode: '123456',
});
const codeTime = ref(0);
const codeTimeContet = computed(() => {
    return codeTime.value;
});

function validatePhone() {
    loginForm.value.phone = formatPhone.value.replace(/\s+/g, '');
    let reg = /^[1][0,1,2,3, 4, 5, 6, 7, 8, 9][0-9]{9}$/;
    return reg.test(loginForm.value.phone);
}
// 手机344分割
function phoneDivision() {
    nextTick(() => {
        let value = formatPhone.value.replace(/\D/g, '').substr(0, 11);
        let len = value.length; // 获取长度判断
        if (len > 3 && len < 8) {
            value = value.replace(/^(\d{3})/g, '$1 ');
        } else if (len >= 8) {
            value = value.replace(/^(\d{3})(\d{4})/g, '$1 $2 ');
        }
        formatPhone.value = value;
    });
}
// 获取验证码
async function getCode() {
    loginForm.value.phone = formatPhone.value.replace(/\s+/g, '');
    if (!loginForm.value.phone) {
        uni.showToast({
            icon: 'none',
            title: '请输入手机号',
        });
        return;
    }
    try {
        const res = await sendCodeMessageApi(loginForm.value.phone);
        uni.showToast({
            title: '发送成功！',
            icon: 'none',
        });
        codeTime.value = 60;
        let timer = setInterval(() => {
            codeTime.value--;
            if (codeTime.value < 1) {
                clearInterval(timer);
                codeTime.value = 0;
            }
        }, 1000);
    } catch (err) {
        console.log(err);
    }
}
// 登录
async function handleLogin() {
    if (!validatePhone() || !loginForm.value.verifyCode) {
        uni.showToast({
            icon: 'none',
            title: '账号或验证码不正确',
        });
        return;
    }
    uni.showLoading({
        title: '登录中...',
    });
    getAdminTypeByPhone();
}
// 用户身份
async function getAdminTypeByPhone() {
    console.log('loginForm.value.phone', loginForm.value.phone);
    const res = await getAdminTypeByPhoneApi({
        phone: loginForm.value.phone,
    });
    console.log('res', res);
    userAdmin.value = res.data;
    if (userAdmin.value.length <= 1) {
        // 非多个身份
        smsLogin();
    } else {
        // 多个身份
        popupRef.value.open();
    }
}
async function smsLogin() {
    console.log('login', loginForm.value);
    const res = await smsLoginApi(loginForm.value);
    // userStore.setToken(res.data);
    setCache('token',res.data)
    uni.setStorageSync('token', res.data);
    const { data } = await getUserInfoApi();
    console.log('datas=--',data)
    if (!data.openid) {
        // 初次注册
        const authRes = await getAuthUrlApi();
        console.log('authRes',authRes)
        // #ifdef H5
        window.location.href = authRes.data;
        console.log('authRes', authRes.data);
        // #endif
    }else{
        uni.switchTab({
            url:'/pages/home/index'
        })
    }
    uni.hideLoading()
}
</script>

<style lang="scss" scoped>
.title_bar {
    z-index: 99;
}

.login_page {
    margin-top: 120rpx;

    .title {
        margin-bottom: 87rpx;
        line-height: 56rpx;
        font-size: 40rpx;
        font-weight: 500;
        color: #333;
        text-align: center;
    }

    .login_form {
        padding: 0 30rpx;

        &_item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 24rpx 30rpx;
            margin-bottom: 40rpx;
            background-color: #fff;
            border-radius: 20rpx;

            .left {
                display: flex;
                align-items: center;

                .input_box {
                    text-align: left;
                    color: rgba(51, 51, 51, 1);
                    font-size: 30rpx;
                    line-height: 42rpx;
                }
            }

            &_icon {
                width: 40rpx;
                height: 40rpx;
                margin-right: 20rpx;
            }

            .code_btn {
                color: rgba(97, 93, 255, 1);
                font-size: 30rpx;
                line-height: 42rpx;
            }
        }

        .phone_btn {
            margin: 60rpx 0 0 0;
            height: 90rpx;
            line-height: 90rpx;
            background-color: #615dff;
            color: #fff;
            font-size: 30rpx;
            border-radius: 20rpx;
        }
    }

    .popup_box {
        background-color: #fff;
        border-radius: 20rpx 20rpx 0 0;
        overflow: hidden;

        .header_title {
            margin: 30rpx 0 0 30rpx;
            color: rgba(51, 51, 51, 1);
            font-size: 32rpx;
            font-weight: 500;
            text-align: left;
        }

        .method_list {
            text-align: center;
            padding: 0 54rpx;

            .item {
                padding: 30rpx 0;
                border-bottom: 1rpx solid rgba(235, 235, 235, 1);
                font-weight: 400;
                height: 45rpx;
                color: rgba(51, 51, 51, 1);
            }
        }
    }
}
</style>
